using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

namespace BehaviorSystem
{
    public class BehaviorFilter
    {
        private int _priority;
        private int _innerPriority;
        private int _optionalBehaviorKey;
        public string _currentBehavior;
        private Dictionary<string, BehaviorInfo> _behaviorReg;

        public BehaviorFilter()
        {
            _behaviorReg = new Dictionary<string, BehaviorInfo>();
            ResetPriorityData();
        }

        public void CoolDown()
        {
            foreach (var item in _behaviorReg.Values) { item.CoolDown(); }
        }

        public void RefreshCD(string key)
        {
            _behaviorReg[key].RefreshCD();
        }

        public bool IsBehaviorActive(string key)
        {
            return _behaviorReg[key].IsActive;
        }

        public void Reg_BehaviorInfo(string key, BehaviorInfo behaviorInfo)
        {
            if (_behaviorReg.ContainsKey(key)) _behaviorReg.Remove(key);//refresh
            _behaviorReg.Add(key, behaviorInfo);
        }

        private void ResetPriorityData()//make sure that each available priorities can be calculated
        {
            _priority = 0;
            _innerPriority = 0;
            _optionalBehaviorKey = 0;
            _currentBehavior = "";
        }

        public bool IsPermitted(string key)
        {
            if (!_behaviorReg[key].IsReady) return false;
            if (_behaviorReg[key].Priority < _priority) return false;
            else if (_behaviorReg[key].Priority == _priority)
            {
                if (_behaviorReg[key].InnerPriority < _innerPriority) return false;
                else if (_behaviorReg[key].InnerPriority == _innerPriority &&
                    _behaviorReg[key].BehaviorKey != _optionalBehaviorKey) return false;
            }
            return true;
        }

        public void ActiveBehavior(string key)
        {
            _priority = _behaviorReg[key].Priority;
            _innerPriority = _behaviorReg[key].InnerPriority;
            _optionalBehaviorKey = _behaviorReg[key].OptionalBehaviorKey;
            _behaviorReg[key].Activate();
            _behaviorReg[key].ResetCD();
            _currentBehavior = key;
        }

        public void Deactivate()
        {
            if (_behaviorReg.ContainsKey(_currentBehavior)) _behaviorReg[_currentBehavior].Deactivate();
            ResetPriorityData();
        }
    }
}